package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.service.IAppletService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AppletServiceImpl
 * @Description TODO
 * @Author ZYJ
 * @Date 2024/4/15 15:59
 * @Version 1.0
 **/
@Service
public class AppletServiceImpl implements IAppletService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Resource
    private RestTemplate restTemplate;

    //小程序的AppID和AppSecret
    private final String appId = "wx68a38dcd8cef827e";
    private final String appSecret = "d4e503cd0e7157d12bb6eda232cee2a2";

    /**
     * 登录凭证校验,获取用户openId
     * @param code
     * @return
     */
    @Override
    public JSONObject getCheckByCode(String code) {

        //构建请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        //发送请求
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        System.out.println("获取openid请求响应:"+responseEntity);
        if (responseEntity.getStatusCodeValue() != 200 || Objects.isNull(responseEntity.getBody())) {
            throw new RuntimeException("OpenId接口调用异常~");
        }
        return JSON.parseObject(responseEntity.getBody());
    }


    /**
     * 解析小程序用户手机号
     * @param mobileCode
     * @return
     */
    @Override
    public String getAppletUserPhone(String mobileCode) {
        //获取微信小程序token
        String appletToken = getAppletToken();

        //构建请求URL
        String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+appletToken;

        //封装请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", mobileCode);

        //发送请求
        ResponseEntity<HashMap> responseEntity = restTemplate.postForEntity(url, paramMap, HashMap.class);
        System.out.println("获取手机号请求响应:"+responseEntity);
        if (responseEntity.getStatusCodeValue() != 200 || Objects.isNull(responseEntity.getBody()) || (Integer) responseEntity.getBody().get("errcode")!=0) {
            throw new RuntimeException("解析手机号接口调用异常~");
        }
        System.out.println("微信手机授权请求解析手机号返回: " + responseEntity.getBody());

        LinkedHashMap phoneInfo = (LinkedHashMap)responseEntity.getBody().get("phone_info");

        return (String)phoneInfo.get("purePhoneNumber");
    }

    /**
     * 获取微信请求token
     * @return
     */
    public String getAppletToken(){
        // 查询redis 是否有存放access_token避免过多次请求
        String appletToken = redisTemplate.opsForValue().get("appletToken");
        if (Strings.isNotEmpty(appletToken)){
            return appletToken;
        }

        //构建请求URL
        String url = "https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=client_credential"+
                "&appid=" + appId +
                "&secret=" + appSecret;

        ResponseEntity<HashMap> responseEntity = restTemplate.getForEntity(url, HashMap.class);
        System.out.println("获取token请求响应:"+responseEntity);
        if (responseEntity.getStatusCodeValue()!=200||Objects.isNull(responseEntity.getBody())|| Objects.nonNull(responseEntity.getBody().get("errcode"))){
            throw new RuntimeException("获取Token接口调用异常~");
        }
        System.out.println("微信手机授权请求AccessToken返回:"+ responseEntity.getBody());
        String token = responseEntity.getBody().get("access_token").toString();
        //存入redis，设置过期时间2小时
        redisTemplate.opsForValue().set("appletToken",token,2, TimeUnit.HOURS);
        return token;
    }
}
